#include <Arduino.h>
#include <String.h>
//#define rpin 11  //red
//#define gpin 10  //green
//#define bpin 9   //blue
//
//void setup() {
//  // put your setup code here, to run once:
//  Serial.begin(9600);
//  while(!Serial){;};
//  pinMode(rpin,OUTPUT);
//  pinMode(gpin,OUTPUT);
//  pinMode(bpin,OUTPUT);
//   pinMode(13, OUTPUT); digitalWrite(13, LOW);
//}
//
//void loop() {
//  // put your main code here, to run repeatedly:
//  static int i = 0;
//  if(i == 3){
//      i = 0;
//    }
//  switch(i){
//    case 0: analogWrite(rpin,0);  //红 0 255 255         
//            analogWrite(gpin,255); //绿 255 0 255
//            analogWrite(bpin,255); //蓝 255 255 0
//            delay(100); break;
//    case 1: analogWrite(rpin,255);  //红 0 255 255         
//            analogWrite(gpin,0); //绿 255 0 255
//            analogWrite(bpin,255); //蓝 255 255 0
//            delay(100); break;
//    case 2: analogWrite(rpin,255);  //红 0 255 255         
//            analogWrite(gpin,255); //绿 255 0 255
//            analogWrite(bpin,0); //蓝 255 255 0
//            delay(100); break;
//    }
//    i++;
//    Serial.print(analogRead(rpin));
//    Serial.print("-");
//    Serial.print(analogRead(gpin));
//    Serial.print("-");         
//    Serial.println(analogRead(bpin));         
//    delay(1000);
//}

//默认为红灯
unsigned short int red = 0, green = 0, blue = 0;
char *r,*g,*b;
char buf[13] = "NULL";

void setup() {
 // 打开串口通讯功能等待串口打开
 Serial.begin(250000);
 while (!Serial) {
 ; // wait for serial port to connect. Needed for Leonardo only
 }
 // 发送信息
 Serial.println(255,BIN);
 Serial.println(255,OCT);
 Serial.println(255,HEX);
 Serial.println();
 // 设置 led 端口方向:
 pinMode(7, OUTPUT);
 pinMode(10, OUTPUT);
 pinMode(11, OUTPUT);
 // 打开 13 脚 led 作为电源指示:
 pinMode(13, OUTPUT);
 digitalWrite(13, LOW);
 //默认红灯
 analogWrite(11, 0);
 analogWrite(10, 255);
 analogWrite(7, 255);
}
//主循环
void loop() {
 int inChar = 0;
 int flag = 0;
 // 读取串口发送的信息:
 if (Serial.available() > 0) {
  Serial.println("----------------ok------------------");
  Serial.readBytes(buf, 13);   //提取串口中的字符串
  int count = 1;
  char *temp = strtok(buf,",");  //进行分割字符串
  while(temp)
  {
        switch(count){
            case 1: r = temp;break;
            case 2: g = temp;break;
            case 3: b = temp;break;
          }
        temp = strtok(NULL,","); //如果查不到delimiter所标示的字符，则返回当前strtok的字符串的指针。
        count++;
  }
  inChar = 1;
}else{
   flag = 1;
}
 // 如果输入的是回车符号，就是最后一个数据
 if (inChar == 1) 
 {
  red = atoi(r);   
  green = atoi(g);
  blue = atoi(b);
  Serial.print("Red: ");
  Serial.print(red);
  Serial.print(", Green: ");
  Serial.print(green);
  Serial.print(", Blue: ");
  Serial.println(blue);
 
 // 写入对应的 PWM 值
  analogWrite(11, 255 - red);
  analogWrite(10, 255 - green );
  analogWrite(9, 255 - blue);
 }
}
